package com.d7024e.QADgui;

import java.awt.Canvas;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Panel;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.geom.Ellipse2D;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.swing.BoxLayout;

import com.ekahau.engine.sdk.DeviceLocation;
import com.ekahau.engine.sdk.EngineException;
import com.ekahau.engine.sdk.IDeviceLocationListener;
import com.ekahau.engine.sdk.Model;
import com.ekahau.engine.sdk.ModelMap;
import com.ekahau.engine.sdk.PositioningEngine;


public class QuickAndDirtyFrame extends java.awt.Frame {
	/**
	 * 
	 */
	private static final long serialVersionUID = 6777856959608511760L;
	static {
		// Only log warnings
		System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog");
		System.setProperty("org.apache.commons.logging.simplelog.showdatetime", "true");
		System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.commons.httpclient", "warn");
	}
	
	private class EkahauConfig{
		// Default values
		private static final String DEFAULT_HOSTNAME = "130.240.233.27";
		private static final int DEFAULT_PORT = 8550;
		private static final String DEFAULT_USERNAME = "mdcs";
		private static final String DEFAULT_PASSWORD = "mdcs";
		
		String hostname = DEFAULT_HOSTNAME;
		int port = DEFAULT_PORT;
		String username = DEFAULT_USERNAME;
		String password = DEFAULT_PASSWORD;
	}
	private class MapBackground extends Panel{
		/**
		 * 
		 */
		private static final long serialVersionUID = -7170504247189622048L;

		@Override
		public void paint(Graphics g) {
			System.out.println("mapBackground paint called !");

//			super.paint(g);
			Graphics2D g2 = (Graphics2D) g;
			
			try {
				Model model = _ekahauEngine.getActiveModel();
				Collection<ModelMap> maps = (Collection<ModelMap>) model.getMaps();
				System.out.println("we have "+maps.size()+" maps");
				Iterator<ModelMap> ite = maps.iterator();
				if(ite.hasNext()){
					ModelMap oneMap = ite.next();
					Image img = oneMap.renderMapImage();
					g2.drawImage(img, 0,0, this);
				}
			} catch (EngineException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
//			for (Component comp : this.getComponents()) {
//				comp.paint(g);
//			}
			super.paint(g);
		}
	}
	private class DeviceMarker extends Component{
		/**
		 * 
		 */
		private static final long serialVersionUID = 5389981340377961823L;
		
		private int _x = 0;
		private int _y = 0;
		private int _color = (int) (Math.random()*255);
		private static final int DEFAULT_SIZE_X = 20;
		private static final int DEFAULT_SIZE_Y = 20;
		private int _sizeX = DEFAULT_SIZE_X;
		private int _sizeY = DEFAULT_SIZE_Y;
		@Override
		public void paint(Graphics g) {
			//super.paint(g);
			Graphics2D g2 = (Graphics2D) g;
			Ellipse2D circle = new Ellipse2D.Float(0,0, _sizeX, _sizeY);
			System.out.println("drawing a circle for a DeviceMarker");
			g2.setColor(new Color(_color));
//			g2.draw(circle);
			g2.fill(circle);
			g2.translate(_x,_y);
		}
		public void setLoc(int x, int y){
			System.out.println("Lets set the location here !!!!! !!! ! ! ! !");
			_x = x; _y = y;
			repaint(0);
		}
	}
	/*
	 * UI elements
	 */
	private MapBackground _mainpanel;
	private Map<String, DeviceMarker> _markers;
	
	/*
	 * core elements
	 */
	private PositioningEngine _ekahauEngine;
	
	public QuickAndDirtyFrame() {
		//first create a Caneva to draw both the image and pointer !
		EkahauConfig config = new EkahauConfig();
		//if necessary : make the configuration adjustement here ! 
		_ekahauEngine = new PositioningEngine(config.hostname, config.port, config.username, config.password);
		_markers = new HashMap<String, DeviceMarker>();
		//first : list all the devices : 
		_mainpanel = new MapBackground();
		this.setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
		this.add(_mainpanel);
		this.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				System.exit(0);
			}
		});
		this.setTitle("Quick and Dirty try  ! ");
		initDevices();
//		dirtyMarkerPrinting();
		this.setPreferredSize(new Dimension(400, 500));
		_mainpanel.repaint();
		this.pack();
		
		//init the listener ! 
		try {
			startListening();
		} catch (EngineException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	private void dirtyMarkerPrinting() {
		//adding to the window ! 
		DeviceMarker tempMarker = new DeviceMarker();
//		this.add(tempMarker);
//		tempMarker.setLoc(5, 5);
//		tempMarker = new DeviceMarker();
//		this.add(tempMarker);
//		tempMarker.setLoc(10, 10);
//		tempMarker = new DeviceMarker();
//		this.add(tempMarker);
//		tempMarker.setLoc(15, 15);
//		tempMarker = new DeviceMarker();
//		this.add(tempMarker);
//		tempMarker.setLoc(25, 25);
//		
		
		tempMarker = new DeviceMarker();
		_mainpanel.add(tempMarker);
		tempMarker.setLoc(15, 5);
		tempMarker = new DeviceMarker();
		_mainpanel.add(tempMarker);
		tempMarker.setLoc(20, 10);
		tempMarker = new DeviceMarker();
		_mainpanel.add(tempMarker);
		tempMarker.setLoc(25, 15);
		tempMarker = new DeviceMarker();
		_mainpanel.add(tempMarker);
		tempMarker.setLoc(35, 25);
		
	}
	private void startListening() throws EngineException{
		_ekahauEngine.addLocationListener(new IDeviceLocationListener() {
			@Override
			public void newDeviceLocation(DeviceLocation arg0) {
				String mac = arg0.getMAC();
				String name = arg0.getName();
				Integer x = arg0.getX(), y = arg0.getY();
				System.out.println("new LocationEvent for the device "+name+" "+mac+"\t ("+x+";"+y+")");
				if(x != null && y != null){
					System.out.println("lets assigne the new location ! ");
					_markers.get(mac).setLoc(20, 20);
				}
			}
			@Override
			public void connectionClosed(Exception arg0) {
				System.out.println("connection closed with the engine !");
			}
		});
		_ekahauEngine.startTracking();
	}
	private void initDevices() {
		try {
			List<DeviceLocation> devices = _ekahauEngine.findDevices();
			Iterator<DeviceLocation> ite = devices.iterator();
			while (ite.hasNext()) {
				DeviceLocation dev = (DeviceLocation) ite.next();
				String mac = dev.getMAC();
				System.out.println("Device MAC : "+mac+"\tlocated at : ("+dev.getX()+';'+dev.getY()+')');
				//let's create a new marker for it !
				if(_markers.get(mac) == null){
					DeviceMarker marker = new DeviceMarker();
					_mainpanel.add(marker);
					_markers.put(mac, marker);
				}else{
					// TODO 
				}
			}
		} catch (EngineException e) {
			e.printStackTrace();
			
		}
	}

	public static void main(String[] args) {
		QuickAndDirtyFrame main = new QuickAndDirtyFrame();
		main.setVisible(true);
		
	}
}
